import { Component, OnInit, ElementRef, AfterContentInit, Inject, Optional, ContentChild } from '@angular/core';
import { BaseView } from '../../core/view/base-view';
import { NavigationEnd } from '@angular/router';
import { ENABLED_QUERY_PAGE_COLLAPSE } from '../keys';
import { DxDataGridComponent } from 'devextreme-angular/ui/data-grid';

@Component({
  selector: 'bz-table-panel',
  templateUrl: './table-panel.component.html'
})
export class TablePanelComponent<U, B, S> extends BaseView<U, B, S> implements OnInit, AfterContentInit {

  @ContentChild(DxDataGridComponent, { static: true }) dataGrid: DxDataGridComponent;
  viewInfo;
  nzTabsets;
  private collapse: any;
  private tableContentEle: Element;

  constructor(
    private hostEle: ElementRef,
    @Optional() @Inject(ENABLED_QUERY_PAGE_COLLAPSE) private enabledQueryPageCollapse = false
  ) {
    super();
  }

  ngOnInit() {
    if (this.enabledQueryPageCollapse === true) {
      // this.hostEle.nativeElement.addEventListener('wheel', this.onWheel.bind(this), { passive: true }, true);

      this.router.events.subscribe(e => {
        if (!(e instanceof NavigationEnd)) {
          return;
        }
        this.collapse = false;
        this.broadcastService.emit(<any>'QueryPageCollapse', false);
      });
    }
  }

  ngAfterContentInit(): void {
    // this.ngZone.runOutsideAngular(() => {
    //   setTimeout(() => {
    //     this.tableContentEle = this.hostEle.nativeElement.querySelector('.dx-datagrid-rowsview .dx-datagrid-content.dx-pointer-events-target');
    //     this.viewInfo = document.querySelector('bz-view-info');
    //     this.nzTabsets = document.querySelectorAll('nz-tabset');
    //   }, 100);
    // });
    if (this.dataGrid) {
      this.dataGrid.pager.visible = true;
    }
  }

  private onWheel(e: WheelEvent) {
    if (!this.tableContentEle || e.shiftKey) {
      return;
    }

    if (e.deltaY > 0 && this.tableContentEle.scrollHeight > this.tableContentEle.clientHeight && this.collapse !== true) {
      this.broadcastService.emit(<any>'QueryPageCollapse', true);
      this.collapse = true;
      e.stopPropagation();
    } else if (e.deltaY < 0 && this.tableContentEle.scrollTop <= 0 && this.collapse !== false) {
      this.broadcastService.emit(<any>'QueryPageCollapse', false);
      this.collapse = false;
    }
  }
}
